package cn.bfay.lion.jingdong.service.impl;

import cn.bfay.cache.redis.RedisKeyBuilder;
import cn.bfay.cache.redis.RedisTime;
import cn.bfay.cache.redis.RedisUtils;
import cn.bfay.lion.jingdong.entity.ProductDetailInfo;
import cn.bfay.lion.jingdong.mapper.ProductDetailInfoMapper;
import cn.bfay.lion.jingdong.redis.RedisKeyTemplate;
import cn.bfay.lion.jingdong.service.ProductDetailInfoService;
import cn.bfay.lion.jingdong.vo.ProductDetailInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * MESSAGE.
 *
 * @author wangjiannan
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ProductDetailInfoServiceImpl implements ProductDetailInfoService {
    private final ProductDetailInfoMapper productDetailInfoMapper;

    @Override
    public List<ProductDetailInfoVo> getProductDetailInfos(String skuid) {
        String redisKey = RedisKeyBuilder.generateRedisKey(RedisKeyTemplate.PRODUCT_DETAIL_INFOS_TEMPLATE, skuid);
        TypeReference<List<ProductDetailInfo>> typeReference = new TypeReference<List<ProductDetailInfo>>() {
        };
        List<ProductDetailInfo> productDetailInfos = RedisUtils.getValue(redisKey, typeReference);
        if (CollectionUtils.isEmpty(productDetailInfos)) {
            productDetailInfos = productDetailInfoMapper.selectList(new QueryWrapper<ProductDetailInfo>().lambda()
                .eq(ProductDetailInfo::getSkuid, skuid)
                .orderByDesc(ProductDetailInfo::getCreateTime)
                .last("limit 80"));
            if (CollectionUtils.isNotEmpty(productDetailInfos)) {
                // 反转成正序
                Collections.reverse(productDetailInfos);
                RedisUtils.setValue(redisKey, productDetailInfos, RedisTime.WEEK);
            }
        } else {
            log.debug("缓存获取productDetailInfos");
        }
        return processVoData(productDetailInfos);
    }

    private List<ProductDetailInfoVo> processVoData(List<ProductDetailInfo> productDetailInfos) {
        List<ProductDetailInfoVo> productDetailInfoVos = new ArrayList<>(productDetailInfos.size());
        productDetailInfos.forEach(productDetailInfo -> {
            ProductDetailInfoVo productDetailInfoVo = new ProductDetailInfoVo();
            BeanUtils.copyProperties(productDetailInfo, productDetailInfoVo);
            productDetailInfoVos.add(productDetailInfoVo);
        });
        return productDetailInfoVos;
    }

}
